<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <!-- 购物车列表 -->
      <div v-if="cartList.length" class="cart-body">
        <ul v-for="(c, index) in cartList" :key="c.id" class="cart-list">
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              :checked="c.isChecked"
              @change="changeOneChecked(c)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="c.imgUrl" />
            <div class="item-msg">{{ c.skuName }}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ c.skuPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <a @click="changeNum('decre', c)" class="mins">-</a>
            <input
              autocomplete="off"
              type="text"
              :value="c.skuNum"
              @change="changeNum('input', c, $event)"
              minnum="1"
              class="itxt"
            />
            <a @click="changeNum('incre', c)" class="plus">+</a>
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ c.skuPrice * c.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a @click="deleteOneGoods(c.skuId, index)" class="sindelet">删除</a>
            <br />
          </li>
        </ul>
      </div>
    </div>
    <!-- 统计 -->
    <div class="cart-tool" v-if="cartList.length">
      <div class="select-all">
        <input
          class="chooseAll"
          type="checkbox"
          :checked="isCheckedAll"
          @change="checkedAll"
        />
        <span>全选</span>
      </div>
      <div class="option">
        <a @click="bactchDeleteChecked">删除选中的商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ cartTotal }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ cartAllPrice }}</i>
        </div>
        <div class="sumbtn">
          <router-link to="/trade" class="sum-btn">结算</router-link>
        </div>
      </div>
    </div>

    <div v-if="!cartList.length" class="empty">
      <h1>购物车空空如也！</h1>
      <img src="http://49.232.112.44/img/empty.751bed26.gif" alt="" />
    </div>
  </div>
</template>

<script>
import {
  ReqGetCartList,
  ReqCheckOneCart,
  ReqBatchChecked,
  ReqDeleteOneGoods,
  ReqBatchDeleteCart,
  ReqAddToCart,
} from "@/api";
import { regNum } from "@/utils/reg";

import _ from "lodash";

export default {
  name: "ShopCart",
  data() {
    return {
      cartList: [],
    };
  },
  methods: {
    //初始化获取 购物车数据
    async getCartList() {
      let result = await ReqGetCartList();
      // console.log(result);
      //赋值
      result[0] ? (this.cartList = result[0].cartInfoList) : null;
    },
    // 更新单个商品选中
    async changeOneChecked(value) {
      // console.log(value);
      //获取传递的数据
      let { isChecked, skuId } = value;
      //改变 选中状态的值
      let newIsChecked = isChecked === 1 ? 0 : 1;
      //发送请求
      await ReqCheckOneCart(skuId, newIsChecked);

      //更新 当前商品的选中状态
      value.isChecked = newIsChecked;
    },
    //更新全部商品的选中
    async checkedAll(e) {
      // console.log(value);

      //获取选中状态
      let isChecked = e.target.checked === true ? 1 : 0;

      //准备所有商品的id
      let skuIdList = this.cartList.map((item) => item.skuId);
      // console.log(skuIdList);

      //发送请求更新全部状态
      await ReqBatchChecked(isChecked, skuIdList);
      //更新前端 所有商品的选中状态
      this.cartList.forEach((item) => (item.isChecked = isChecked));
    },
    //删除单个商品
    async deleteOneGoods(skuId, index) {
      this.$confirm("确定删除吗？", "", {
        type: "warning",
        center: true,
      })
        .then(async () => {
          //  1. 向后台发送请求删除单个数据
          await ReqDeleteOneGoods(skuId);
          // console.log(result);
          //  2. 更新前端的数据  [第一种形式]
          // this.cartList = this.cartList.filter( item => item.skuId !== skuId)

          //  2. 更新前端的数据  [第二种形式]
          this.cartList.splice(index, 1);

          //3. 提示
          this.$message.success("删除成功！");
        })
        .catch(() => {});
    },
    //批量删除选中的商品
    async bactchDeleteChecked() {
      // 收集 要删除的商品的 skuId
      let skuIdList = [];
      this.cartList.forEach((item) => {
        if (item.isChecked === 1) {
          skuIdList.push(item.skuId);
        }
      });

      //判断是否有选中的商品可进行删除
      if (!skuIdList.length) return;

      this.$confirm("确定删除选中的商品吗?", "温馨提示", {
        type: "warning",
      })
        .then(async () => {
          // 1. 向后台发送请求删除数据
          await ReqBatchDeleteCart(skuIdList);

          // 2. 更新前端的数据
          this.cartList = this.cartList.filter(
            (item) => !skuIdList.includes(item.skuId)
          );

          //3. 提示
          this.$message.success("删除成功！");
        })
        .catch(() => {});
    },
    //函数节流   加减按钮  减轻服务器压力，真实项目就可以了
    /*  changeNum: _.throttle(async (type, value, e)=>{
      //判断 更新类型
      switch (type) {
        case "input":
          //获取id 和 老数量
          let { skuId, skuNum } = value;
          //新数据
          let newNum = e.target.value;
          //差值
          let distNum = newNum - skuNum;
          //正则验证 范围 1-200
          if (regNum.test(newNum)) {
            //符合 1-200 范围
            //向后台发送请求  更新数量
            await ReqAddToCart(skuId, distNum);

            //更新当前商品的选中状态
            value.isChecked = 1;
            //更新前端的商品数量
            value.skuNum = newNum;
          } else if (newNum > 200) {
            //  输入的数据大于 200
            //向后台发送请求  更新数量
            await ReqAddToCart(skuId, 200 - skuNum);
            //更新当前商品的选中状态
            value.isChecked = 1;
            //更新前端的商品数量
            value.skuNum = e.target.value = 200;
          } else {
            //更新前端的商品数量
            e.target.value = value.skuNum;
          }

          break;
        case "incre":
          if(value.skuNum < 200){
               //向后台发送请求  更新数量
              await ReqAddToCart(value.skuId, 1);
              //更新当前商品的选中状态
              value.isChecked = 1;
              //当前数据+1
              value.skuNum ++;
          }
          break;
        case "decre":
          if(value.skuNum > 1){
               //向后台发送请求  更新数量
              await ReqAddToCart(value.skuId, -1);
              //更新当前商品的选中状态
              value.isChecked = 1;
              //当前数据+1
              value.skuNum --;
          }
          break;
      }
    },5000,{trailing:false}) */

    //更新商品数量  因为后台没做数据验证
    async changeNum(type, value, e) {
      //向 当前组件对象添加一个属性 锁
      this.isLock; //锁

      if (this.isLock) return;

      //判断 更新类型
      switch (type) {
        case "input":
          // 上锁；
          this.isLock = true;
          //获取id 和 老数量
          let { skuId, skuNum } = value;
          //新数据
          let newNum = e.target.value;
          //差值
          let distNum = newNum - skuNum;
          //正则验证 范围 1-200
          if (regNum.test(newNum)) {
            //符合 1-200 范围
            //向后台发送请求  更新数量
            await ReqAddToCart(skuId, distNum);

            //更新当前商品的选中状态
            value.isChecked = 1;
            //更新前端的商品数量
            value.skuNum = newNum;
          } else if (newNum > 200) {
            //  输入的数据大于 200
            //向后台发送请求  更新数量
            await ReqAddToCart(skuId, 200 - skuNum);
            //更新当前商品的选中状态
            value.isChecked = 1;
            //更新前端的商品数量
            value.skuNum = e.target.value = 200;
          } else {
            //更新前端的商品数量
            e.target.value = value.skuNum;
          }

          break;
        case "incre":
          // 上锁；
          this.isLock = true;
          if (value.skuNum < 200) {
            //向后台发送请求  更新数量
            await ReqAddToCart(value.skuId, 1);
            //更新当前商品的选中状态
            value.isChecked = 1;
            //当前数据+1
            value.skuNum++;
          }
          break;
        case "decre":
          // 上锁；
          this.isLock = true;
          if (value.skuNum > 1) {
            //向后台发送请求  更新数量
            await ReqAddToCart(value.skuId, -1);
            //更新当前商品的选中状态
            value.isChecked = 1;
            //当前数据+1
            value.skuNum--;
          }
          break;
      }

      //解锁
      this.isLock = false;
    },
  },
  computed: {
    //计算全选与取消全选
    isCheckedAll: {
      get() {
        return this.cartList.every((item) => item.isChecked === 1);
      },
      // async set(value){
      //   // console.log(value);
      //   //获取选中状态
      //   let isChecked = value ? 1 : 0;

      //   //准备所有商品的id
      //   let skuIdList = this.cartList.map(item => item.skuId);
      //   // console.log(skuIdList);

      //   //发送请求更新全部状态
      //   await ReqBatchChecked(isChecked,skuIdList);
      //   //更新前端 所有商品的选中状态
      //   this.cartList.forEach(item => item.isChecked = value ? 1 : 0);

      // }
    },
    // 计算商品总数量
    cartTotal() {
      return this.cartList.reduce((prev, item) => {
        if (item.isChecked === 1) {
          prev += item.skuNum * 1;
        }
        return prev;
      }, 0);
    },
    //计算总价
    cartAllPrice() {
      return this.cartList.reduce((prev, item) => {
        if (item.isChecked === 1) {
          prev += item.skuPrice * item.skuNum;
        }

        return prev;
      }, 0);
    },
  },
  mounted() {
    //向后台发送请求获取购物车数据
    this.getCartList();
  },
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 31px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;
        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
          text-decoration: none;
          &hover {
            color: white !important;
          }
        }
      }
    }
  }

  .empty {
    margin-top: 50px;
    text-align: center;
    color: gray;
    img {
      width: 300px;
    }
  }
}
</style>